package com.example.homework3

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class FourthActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_fourth)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val takePhotoButton=findViewById<Button>(R.id.photo_button)

        takePhotoButton.setOnClickListener {
            dispatchTakePictureListener()
        }

        val close=findViewById<Button>(R.id.close_button2)
        close.setOnClickListener {
            finish()
        }
    }
    val REQUEST_IMAGE_CAPTURE=1
    // 调用系统相机拍照
    @SuppressLint("QueryPermissionsNeeded")
    private  fun dispatchTakePictureListener(){
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if(intent.resolveActivity(packageManager)!=null){
            startActivityForResult(takePictureIntent,REQUEST_IMAGE_CAPTURE)
        }
        else{
            Toast.makeText(this,"没有找到相机应用",Toast.LENGTH_SHORT).show()
        }
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?,
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==REQUEST_IMAGE_CAPTURE && resultCode==RESULT_OK){
            val imageBitmap=data?.extras?.get("data") as? Bitmap

            imageBitmap?.let{
                val photoImageView=findViewById<ImageView>(R.id.imageView)
                photoImageView.setImageBitmap(it)
                Toast.makeText(this,"拍照成功！",Toast.LENGTH_SHORT).show()
            }

        }

    }

}